﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web.Mvc;
using MvcEngine.Core;
using MvcEngine.Core.Repositories;
using MvcEngine.Core.Extensions;
using MvcEngine.Core.Helpers;
using MvcEngine.Mvc.Extensions;

namespace MvcEngine.Mvc
{
    public class RolePermissionAttribute : AuthorizeAttribute
    {
        private string roleName = null;

        public RolePermissionAttribute(string roleName)
        {
            this.roleName = roleName;
        }

        public override void OnAuthorization(AuthorizationContext filterContext)
        {
            if (!UserContext.Current.User.IsAuthenticated())
            {
                UrlHelper url = new UrlHelper(filterContext.RequestContext);
                filterContext.Result = new RedirectResult(url.LogOn() + "?returnUrl=" + filterContext.HttpContext.Server.UrlEncode(filterContext.HttpContext.Request.Url.AbsolutePath));
                return;
            }

            if (UserContext.Current.User.IsInRole(roleName))
                return;

            throw new PermissionException("You don't have permissions.");
        }
    }
}
